package org.example.message_queue.mqserver.datacenter;

import org.example.message_queue.common.MqException;
import org.example.message_queue.mqserver.core.Binding;
import org.example.message_queue.mqserver.core.Exchange;
import org.example.message_queue.mqserver.core.MSGQueue;
import org.example.message_queue.mqserver.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/*
* 管理所有硬盘上的数据
* 1.数据库：交换机、绑定、队列
* 2.数据文件：消息
*/
public class DiskDataCenter {
    private DataBaseManager dataBaseManager = new DataBaseManager();
    private MessageFileManager messageFileManager = new MessageFileManager();

    public void init(){
        dataBaseManager.init();
        messageFileManager.init();
    }

//    封装交换机操作
    public void insertExchange(Exchange exchange){
        dataBaseManager.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName){
        dataBaseManager.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExchanges(){
        return dataBaseManager.selectAllExchanges();
    }


//    封装队列操作
    public void insertQueue(MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
//      创建队列的同时，不仅仅是要把队列写入数据库中，还需要创建出对应的目录和文件
        messageFileManager.createQueueFiles(queue.getName());

    }

    public void deleteQueue(String queueName) throws IOException {
        dataBaseManager.deleteQueue(queueName);
//      删除队列的同时，不仅仅是要把队列从数据库中删除，还需要删除对应的目录和文件
        messageFileManager.destroyQueueFiles(queueName);
    }

    public List<MSGQueue> selectAllQueues(){
        return dataBaseManager.selectAllQueue();
    }

//    封装绑定操作
    public void insertBinding(Binding binding){
        dataBaseManager.insertBinding(binding);
    }

    public void deleteBinding(Binding binding){
        dataBaseManager.deleteBinding(binding);
    }

    public List<Binding> selectAllBindings(){
        return dataBaseManager.selectAllBinding();
    }

//    封装消息操作
//    发送消息
    public void sendMessage(MSGQueue queue, Message message) throws IOException, MqException {
        messageFileManager.sendMessage(queue,message);
    }

//    删除消息  --> 思考是否要出发gc
    public void deleteMessage(MSGQueue queue, Message message) throws IOException, ClassNotFoundException, MqException {
        messageFileManager.deleteMessage(queue,message);
        if (messageFileManager.checkGC(queue.getName())){
            messageFileManager.gc(queue);
        }
    }

//    加载所有消息
    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws IOException, MqException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueur(queueName);
    }
}
